/**
 * FileName: QrCodeUtils
 * Author:   Leopold
 * Date:     2018/9/14 16:11
 * Description:
 * History:
 */
package cn.mcsys.myadmin.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;

public class QrCodeUtils {

    public static String createQRCode(String content, String path) throws IOException {
        int width = 300;
        int height = 300;
        String format = "png";

        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encode1 = base64Encoder.encode(content.getBytes());
        System.out.println(encode1);
        byte[] bytes = new BASE64Decoder().decodeBuffer(encode1);
        System.out.println(new String(bytes,"utf-8"));



        //定义二维码的参数
        HashMap map = new HashMap();
        //设置编码
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置纠错等级
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 2);
        String filename = null;
        try {
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(encode1, BarcodeFormat.QR_CODE, width, height);
            File qrDir = new File(path);
            if (!qrDir.exists()) {
                qrDir.mkdir();
            }
            filename = content.replaceAll("/", "-")+".png";
            Path file = new File(path+filename).toPath();
            System.out.println("==========================="+path+filename+"========================");
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return filename;
    }
}
